package com.shop.dao.impl;

import com.shop.util.JDBCUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public abstract class BaseDao {

    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 更新
     * @param sql
     * @param args
     * @return
     */
    public int update(String sql,Object ... args){
        try {
            return queryRunner.update(JDBCUtils.getConnection(),sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询一个
     * @param type
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T queryForOne(Class<T> type, String sql, Map<String,String> map, Object ... args){

        try {
            //注意new BeanHandler<T>(type,new BasicRowProcessor(new BeanProcessor(map))只能在1.7后的dbUtils中使用
            return queryRunner.query(JDBCUtils.getConnection(),sql,new BeanHandler<T>(type,new BasicRowProcessor(new BeanProcessor(map))),args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {

        }

    }

    /**
     * 查询多个
     * @param type
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> List<T> queryForList(Class<T> type, String sql,Map<String,String> map,Object ... args){
        try {
            return queryRunner.query(JDBCUtils.getConnection(),sql,new BeanListHandler<T>(type,new BasicRowProcessor(new BeanProcessor(map))),args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询唯一数据
     * @param sql
     * @param args
     * @return
     */
    public Object queryOne(String sql,Object ... args){
        try {
            return queryRunner.query(JDBCUtils.getConnection(),sql,new ScalarHandler(),args);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


}
